package com.example.loggingservice.service.impl;

import com.example.loggingservice.entity.OperationLog;
import com.example.loggingservice.mapper.OperationLogMapper;
import com.example.loggingservice.service.LoggingService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class LoggingServiceImpl implements LoggingService {
    private final OperationLogMapper operationLogMapper;

    @Override
    @Transactional
    public void saveLog(OperationLog log) {
        operationLogMapper.insert(log);
    }

    @Override
    public List<OperationLog> getLogs(Long userId, String action) {
        List<OperationLog> logs;
        if (userId != null && StringUtils.hasText(action)) {

            logs = operationLogMapper.findByUserId(userId);
            return logs.stream()
                    .filter(log -> action.equals(log.getAction()))
                    .collect(Collectors.toList());
        } else if (userId != null) {
            logs = operationLogMapper.findByUserId(userId);
        } else if (StringUtils.hasText(action)) {
            logs = operationLogMapper.findByAction(action);
        } else {
            // 如果没有指定任何条件，返回所有日志
            logs = operationLogMapper.findAll();
        }
        return logs;
    }
}
